package com.tianji.remark.task;

import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.remark.constants.RedisConstans;
import com.tianji.remark.domain.dto.LikedTimesDTO;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Description LikedTimesCheckTask
 * @Author apeng
 * @Date 2024-12-28
 */
@Component
@RequiredArgsConstructor
public class LikedTimesCheckTask {

    private static final Logger log = LoggerFactory.getLogger(LikedTimesCheckTask.class);

    private final StringRedisTemplate redisTemplate;

    private final RabbitMqHelper mqHelper;
    //建立集合
    private static final List<String> LIKED_TYPES =  CollUtils.newArrayList("QA","NOTE");

    private static final int POP_COUNT = 30;


    /**
     * 使用定时任务定时监听
     */
    @Scheduled(cron = "0/30 * * * * *")
    public void checkLikedTimes(){
        log.info("执行点赞的定时任务");
        //将zset中的数据批量取出并移除
        for (String type : LIKED_TYPES) {
            String key = RedisConstans.LIKED_TIMES + type;
            Set<ZSetOperations.TypedTuple<String>> tuples = redisTemplate.opsForZSet().popMin(key, POP_COUNT);
            if (CollUtils.isEmpty(tuples)){
                continue;
            }
            List<LikedTimesDTO> dtoList = new ArrayList<>();
            for (ZSetOperations.TypedTuple<String> tuple : tuples) {
                String value = tuple.getValue();
                Double score = tuple.getScore();
                LikedTimesDTO dto = new LikedTimesDTO();
                if (value == null || score == null){
                    continue;//跳出当前循环
                }
                dto.setLikedTimes( score.intValue());
                dto.setBizId(Long.valueOf(value));
                dtoList.add(dto);
            }
            //发送消息
            if (CollUtils.isNotEmpty(dtoList)){
                String exchange = MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
                key = StringUtils.format( MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE , type);
                mqHelper.send(exchange,key,dtoList);
            }
        }
    }
}
